/**
 * Created by KY on 2017/4/19.
 */
define(['ldfw/core','ldfw/utils/format'],function(LDFW){
    String.prototype.width = function(font) {
        let f = font || '12px arial',
            o = $('<div>' + this + '</div>')
                .css({'position': 'absolute', ' height': 'auto','width': 'auto','float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
                .appendTo($('body')),
            w = o[0].clientWidth;
        o.remove();
        return w;
    }
    return LDFW.Component.extend({
        initialize:function(){
            let _this = this,
                tagName = this.el.tagName
            this.formatStyle = this.$el.attr('ld-format-style')
            if(['input','textarea','select'].indexOf(tagName.toLocaleLowerCase())>-1){
                this.$el.on('change',function(event){
                    _this.updateStyle(event.target)
                })
            }else{
                let debounce = _.debounce(this.updateStyle,100)
                let observer = new MutationObserver(function(mutations){
                    mutations.forEach(function(mutation){
                        debounce(mutation.target)
                    })
                })
                let config = {childList: true}
                observer.observe(this.el,config)
            }
        },
        setValue:function(value){
            let tagName = this.el.tagName
            if(['input','textarea','select'].indexOf(tagName.toLocaleLowerCase())>-1){
                this.$el.val(value)
            }else{
                this.$el.text(format('number',this.formatStyle,value))
            }
        },
        updateStyle:function(target){
            let str = target.innerHTML,
                width,maxWidth,fontSize;
            maxWidth = $(target).parent().width();
            fontSize = $(target).css('font-size').replace('px','');
            width = str.width(`${fontSize}px Arial`);
            while(width > maxWidth){
                fontSize=fontSize-2;
                width = str.width(`${fontSize}px Arial`);
            }
            $(target).css('font-size',fontSize)
        }
    });
})